// ****状态管理****
import {createStore, applyMiddleware, combineReducers} from './redux/redux.min'
import logger from './redux/redux-logger'
import mian from './redux/mian'
import thunk from './redux/redux-thunk'
var $http = require('./utils/http.js')
const Store = createStore(combineReducers({...mian}), applyMiddleware(thunk, logger))
import { promisifyAll, promisify } from 'wx-promise-pro'
promisifyAll()
// ****状态管理****

var api = require('./utils/api.js')
var $ = require('./utils/util.js')
var regeneratorRuntime = require('./utils/runtime.js')
var num=0;

App({
  Store,
  $http,
  data: {
    lvl:0,//锁电量
    isPreImg: false, // 是否预览图片
    windowHeight: 0, //窗口的高度
    statusBarHeight: 0, //导航的高度
    windowWidth: 0, //窗口宽度
    scale: 1,  //相对于750比例
    isIOS: '',//是否是ios
    screen: null, // 胶囊按钮信息
    user_info: { // 用户信息
    },
    alimgUrl: '', // 阿里图片url
    ycdmArr:[
      '电流',
      '电压',
      '有功功率',
      '无功功率',
      '功率因数',
      '温度',
      '环境',
      '频率',
      '视在功率',
    ],
    ycdmArr1:[
      '相电流',
      '相电压',
      '线电压',
      '有功功率',
      '无功功率',
      '功率因数',
      '铜排温度',
      '电缆温度',
      '周波',
      '视在功率',
      '环境温度',
      '频率',
      '保护电流',
      '接点温度',
      '电压谐波',
      '电流谐波',
    ],
    area_chartsColors: [
      'rgba(251, 204, 19,.3)', // 黄色
      'rgba(46, 194, 90,.3)',  // 绿色
      'rgba(253, 103, 77,.3)', // 红色
      'rgba(23, 144, 255,.3)', // 蓝色
      'rgba(134, 68, 224,.3)', // 紫色
      'rgba(154, 193, 171,.3)', // 暗灰色
      'rgba(66, 80, 136,.3)', // 深紫色
      'rgba(83, 88, 95,.3)', // 灰色
      'rgba(23, 144, 255,.3)', // 深蓝色
      'rgba(26, 220, 0,.3)', // 绿色
      'rgba(177, 213, 200,.3)', // 
      'rgba(119, 80, 57,.3)', // 
      'rgba(238, 121, 89,.3)', // 
      'rgba(236, 176, 193,.3)', // 
      'rgba(180, 146, 115,.3)', // 
      'rgba(225, 138, 59,.3)', // 
      'rgba(169, 190, 123,.3)', // 
      'rgba(166, 64, 54,.3)', // 
      'rgba(240, 145, 160,.3)', // 
      'rgba(250, 192, 61,.3)', // 
      ],
    line_chartsColors: [
      'rgba(251, 204, 19,.6)',// 黄色
      'rgba(46, 194, 90,.6)', // 绿色
      'rgba(253, 103, 77,.6)',// 红色
      'rgba(23, 144, 255,.6)',// 蓝色
      'rgba(134, 68, 224,.6)',// 紫色
      'rgba(154, 193, 171,.6)',// 暗灰色
      'rgba(66, 80, 136,.6)',// 深紫色
      'rgba(83, 88, 95,.6)', // 灰色
      'rgba(23, 144, 255,.6)', // 深蓝色
      'rgba(26, 220, 0,.6)',// 绿色
      'rgba(177, 213, 200,.3)', // 
      'rgba(119, 80, 57,.3)', // 
      'rgba(238, 121, 89,.3)', // 
      'rgba(236, 176, 193,.3)', // 
      'rgba(180, 146, 115,.3)', // 
      'rgba(225, 138, 59,.3)', // 
      'rgba(169, 190, 123,.3)', // 
      'rgba(166, 64, 54,.3)', // 
      'rgba(240, 145, 160,.3)', // 
      'rgba(250, 192, 61,.3)', // 
    ],
  },
  onLaunch: function (options) { 
    num=0;
    wx.removeStorageSync('locationIgnore');//重置用户的位置定位弹窗提醒设置
    try {
      var res = wx.getSystemInfoSync(); // 获取系统信息 
      this.data.windowHeight = res.windowHeight //可使用窗口高度，单位px
      this.data.windowWidth = res.windowWidth //可使用窗口宽度，单位px
      this.data.statusBarHeight = res.statusBarHeight // 状态栏的高度，单位px
      this.data.mainPaddingTop =  res.model.indexOf("iPhone")>-1 ? 4 : 8 // ？？？
      this.data.scale = res.windowWidth / 375 // 屏幕比
      this.data.isIOS = res.system.indexOf('iOS') > -1 ? true : false // 是否是苹果
      var screen = wx.getMenuButtonBoundingClientRect() // 获取菜单按钮（右上角胶囊按钮）的布局位置信息。坐标信息以屏幕左上角为原点。 
      this.data.screen = {
        width: screen.width, // 胶囊按钮宽度
        height: screen.height,  // 胶囊按钮高度
        left: screen.left, // 胶囊按钮左边值
        top: screen.top, // 胶囊按钮上边值
      }
    } catch (e) {
      console.log(e, '$$错误信息$$')
    }

    this.autoUpdate();
    
    // this.stomp();
    // var token = wx.getStorageSync('token') || 0;
    // //实时定位
    // this.LocationUpdateBackground();
    // this.updateLocation();

  },
  
  onShow(options){
    
     //初始获取定位权限
      // this.realTimeLocation();
  },
  _checkUserLogin(){
    var params = {
      username: wx.getStorageSync("username"),
      password: wx.getStorageSync("password"),
    }
    return new Promise((resolve) => {
      api.$get(api.main.checkUserLogin, params).then((res) => {
        // console.log(res)
        if(res.data.login){
          // console.log("islogin")
        }else{
          wx.removeStorageSync('avatar')
          wx.removeStorageSync('phonenumber')
          wx.removeStorageSync('user_id')
          wx.removeStorageSync('user_name')
          wx.removeStorageSync('locationIgnore')
          wx.removeStorageSync('username')
          wx.removeStorageSync('password')
          // console.log("==========")
          // $.linkurl(`/pages/index/index`,'switchTab')
        }
        resolve(res)
      })
    })

  },
  _selectEnterprise(){//获取企业列表
    return new Promise((resolve) => {
      api.$get(api.main.selectEnterprise).then((res) => {
        resolve(res)
      })
    })
  },
  _selectStation(params) {// 获取站房
    return new Promise((resolve) => {
      api.$get(api.main.selectStation1, params).then((res) => {
        resolve(res)
      })
    })
  },

  _selected() {// 获取所有的企业下的站房列表接口--最终是获取站房
    return new Promise((resolve) => {
    api.$get(api.main.selected).then((res) => { 
        resolve(res)
      })
    })
  },
  _selectTree(){//省市，厂站树
    return new Promise((resolve) => {
      api.$get(api.main.selectTree).then((res) => { 
          resolve(res)
        })
      })
  },
  _selectSchoolTree(){//学校 楼号 树
    return new Promise((resolve) => {
      api.$get(api.main.selectSchoolTree,{"user_id":wx.getStorageSync('user_id')}).then((res) => { 
          resolve(res)
        })
      })
  },
  _selectYcxlm({ station }) {//根据站房获取设备列表--最终是获取设备
    return new Promise((resolve) => {
      api.$get(api.main.selectYcxlm, { station }).then((res) => { 
        resolve(res)
      })
    })
  },

  _total(params) { //二级页面统计数据 
    return new Promise((resolve)=>{
      api.$get(api.main.total, params).then((res) => {
        resolve(res)
      })
    })
  },
//单次获取位置
getLocation:function(){
  return new Promise((resolve)=>{
    wx.getLocation({
      type: 'wgs84',
      success: (res)=> {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy
        console.log("当前经纬度:"+latitude+'----'+longitude);
        var res={"latitude":latitude,"longitude":longitude}
        
        resolve(res)
      }
  
    })

  })
},
//目标地点与当前位置的距离
getDistance(lat2, lng2) {
  return new Promise((resolve)=>{
 var lat1=0;
 var lng1=0;
    // resolve(0.0);
      wx.getLocation({
        type: 'wgs84',
        success: (res)=> {
          lat1 = res.latitude
          lng1 = res.longitude
          var radLat1 = lat1 * Math.PI / 180.0
          var radLat2 = lat2 * Math.PI / 180.0
          var a = radLat1 - radLat2
          var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0
          var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
          s = s * 6378.137// EARTH_RADIUS;
          s = Math.round(s * 10000) / 10000;
         api.$get(api.location.location,{'longitude':lng1,'latitude':lat1});
          resolve(s)
        },
        fail:(res) => {
          // console.log(res)
          wx.getSetting({
            success: (res) => {
              if (!res.authSetting['scope.userLocation']) {
                wx.hideLoading()
                wx.showModal({
                  title: '位置授权失败',
                  content: '您需要将小程序的位置信息授权为\n "使用小程序期间和离开小程序后" \n否则将会影响部分功能的正常使用',
                  confirmText: '前往授权',
                  cancelText:'稍后授权',
                  success(res) {
                    if (res.confirm) {
                      wx.openSetting({
                        complete: (res) => {
                          wx.getLocation({
                            type: 'gcj02',
                            success: res => {
                              that.getNowSituation(res)
                            }
                          })
                        },
                      })
                    } else if (res.cancel) {
                      wx.navigateBack()
                    }
                  }
                })
              }
            },
          })
        }
      })
  })
},


autoUpdate: function () { 
  var self = this
  if (wx.canIUse('getUpdateManager')) {
    const updateManager = wx.getUpdateManager()
    // 检查小程序是否有新版本发布
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本的信息回调
      if (res.hasUpdate) {
        wx.showModal({
          title: '更新提示',
          content: '检查到新版本，是否下载新版本并重启小程序？',
          success: function (res) {
            if (res.confirm) {
              // 下载
              self.downloadAndUpdate(updateManager)
            } else if (res.cancel) {
              // 点击取消，做强制更新操作
              wx.showModal({
                title: '温馨提示',
                content: '必须强制更新哦，旧版本无法正常使用',
                showCancel: false,//隐藏取消按钮
                confirmText: '确定更新',
                success: function (res) {
                  if (res.confirm) {
                    // 再次调用下载，并重启
                    self.downloadAndUpdate(updateManager)
                  }
                }
              })

            }
          }
        })
      }
    })
  } else {
    // 增加用户体验，给出友好提示
    wx.showModal({
      title: '提示',
      content: '当前微信版本过低，无法使用该功能，请升级后重试。'
    })
  }

},

  
  /**
   * 下载新版本并重启
   */
  downloadAndUpdate: function (updateManager) {
    var self = this
    wx.showLoading();

    // 监听小程序有版本更新事件，客户端主动触发
    updateManager.onUpdateReady(function () {
      wx.hideLoading();
      // 新版本下载好，调用applyUpdate
      updateManager.applyUpdate()
    })

    // 监听小程序更新失败事件
    updateManager.onUpdateFailed(function () {
      wx.showModal({
        title: '已经有新版了哦',
        content: '请你删除当前小程序，进行升级哦'
      })
    })
  } ,
  //开启后台定位功能
  LocationUpdateBackground:function(){
    wx.startLocationUpdateBackground({
      success(res) {
        console.log('开启后台定位', res)
      },
      fail(res) {
        console.log('开启后台定位失败', res)
      }
    })
  },
  //获取实时定位
  updateLocation: function(){
    wx.onLocationChange(function(res) {
      // var date=new Date();
      // console.log(num,date.getMinutes().toString()+":"+date.getSeconds().toString())
      if(num%15==1){
        if(wx.getStorageSync("user_id")!=0){
          console.log('location change', res)
          api.$get(api.location.location,{'longitude':res.longitude,'latitude':res.latitude});
        }
      }
      num++;
    })
  },
  //实时定位
    realTimeLocation(){
      //初始获取定位权限
      wx.authorize({
        scope: 'scope.userLocationBackground',
        success: (res) => {
          this.LocationUpdateBackground();
          this.updateLocation();
          var locationTimer = setTimeout(this.updateLocation(), 1000*60);
        },fail:(res)=>{//失败,引导用户打开设置页
          var that=this;
          var localtion=wx.getStorageSync('locationIgnore');
          // console.log("res",res)
          if(!localtion || localtion!="true")
          wx.showModal({
            title: '位置授权失败',
            content: '您需要将小程序的位置信息授权为\n "使用小程序期间和离开小程序后" \n否则将会影响部分功能的正常使用',
            confirmText: '前往授权',
            cancelText:'稍后授权',
            success(res) {
              if (res.confirm) {
                wx.openSetting({
                  complete: (res) => {
                    console.log("authSetting",res.authSetting)
                    if(res.authSetting["scope.userLocationBackground"]){
                      that.LocationUpdateBackground();
                      that.updateLocation();
                    }
                  }
                })
              } else if (res.cancel) {
                wx.setStorageSync('locationIgnore', "true");
                wx.navigateBack()
              }
            }
          })
        }
      })
  },

  stomp(){
    var socketOpen = false
    var socketMsgQueue = []
    function sendSocketMessage(msg) {
        console.log('send msg:')
        // console.log(msg);
        if (socketOpen) {
            wx.sendSocketMessage({
                data: msg
            })
        } else {
            socketMsgQueue.push(msg)
        }
    }

    /////////////////////////////////////////////////////
    var ws = {
        send: sendSocketMessage,
        onopen: null,
        onmessage: null
    }

    wx.connectSocket({
        // url: 'ws://223.244.87.84:15674/ws'
        url:api.url.replace("https://","wss://")+"/wss"
    })
    wx.onSocketOpen(function (res) {
        console.log('WebSocket连接已打开！')

        socketOpen = true
        for (var i = 0; i < socketMsgQueue.length; i++) {
            sendSocketMessage(socketMsgQueue[i])
        }
        socketMsgQueue = []

        ws.onopen && ws.onopen()
    })

    wx.onSocketMessage(function (res) {
        console.log('收到onmessage事件:', res)
        ws.onmessage && ws.onmessage(res)
    })

    var Stomp = require('./utils/stomp.js').Stomp;
    Stomp.setInterval = function () { }
    Stomp.clearInterval = function () { }
    var client = Stomp.over(ws);

    var destination = '/exchange/ruidcn/ruidcn.dist.*.event';
    client.connect('alarm', 'alarm', function (sessionId) {
        console.log('sessionId', sessionId)

        client.subscribe(destination, function (body, headers) {
            // console.log('From MQ:', body);
        });

        client.send(destination, { priority: 9 }, 'hello workyun.com !');
    })
  },
 
    //清理 store form 缓存
    _clearFromCache(){
      Store.dispatch({
        type: 'SET_FROM',
        form: {
    
        },
      })
    },
    _auth_company(){
      return new Promise((resolve) => {
        api.$get(api.auth.auth_company, {}).then((res) => { 
          wx.setStorageSync('auth_company', res.data)
          resolve(res)
        })
      })
    },
    _auth_station(){
      return new Promise((resolve) => {
        api.$get(api.auth.auth_station, {}).then((res) => { 
          wx.setStorageSync('auth_station', res.data)
          resolve(res)
        })
      })
    },
    _auth_project(){
      return new Promise((resolve) => {
        api.$get(api.auth.auth_project, {}).then((res) => { 
          wx.setStorageSync('auth_project', res.data)
          resolve(res)
        })
      })
    },
    _auth_equip(){
      return new Promise((resolve) => {
        api.$get(api.auth.auth_equip, {}).then((res) => { 
          wx.setStorageSync('auth_equip', res.data)
          resolve(res)
        })
      })
    },
    _auth_equip_tree(){
      return new Promise((resolve) => {
        api.$get(api.auth.auth_equip_tree, {}).then((res) => { 
          wx.setStorageSync('auth_equip_tree', res.data)
          resolve(res)
        })
      })
    },
    _selectUserIdByAuth(dept_id){
      return new Promise((resolve) => {
        api.$get(api.auth.selectUserIdByAuth, {'dept_id':dept_id}).then((res) => { 
          wx.setStorageSync('selectUserIdByAuth', res.data)
          resolve(res)
        })
      })
    },

  
})